package com.numberone.master.modules.api.service;

import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.numberone.master.common.service.CrudService;
import com.numberone.master.modules.api.controller.ApiWorkOrderController;
import com.numberone.master.modules.api.dao.ApiWorkOrderDao;
import com.numberone.master.modules.api.entity.ApiAttach;
import com.numberone.master.modules.api.entity.ApiBean;
import com.numberone.master.modules.api.entity.ApiWorkOrder;
import com.numberone.master.modules.oa.dao.WorkOrderDao;
import com.numberone.master.modules.oa.entity.Operation;
import com.numberone.master.modules.oa.entity.WorkOrder;
import com.numberone.master.modules.oa.service.OperationService;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.service.SystemService;

@Service
@Transactional(readOnly = true)
public class ApiWorkOrderService extends CrudService<ApiWorkOrderDao, ApiWorkOrder> {
	
	@Autowired
	private WorkOrderDao workOrderDao;
	
	@Autowired
	private OperationService operationService;
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private OfficeService officeService;
	
	public static Log log = LogFactory.getLog(ApiWorkOrderController.class);
	
	public WorkOrder getWo(String str){
		JSONObject json = JSONObject.fromObject(str);
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject obj = JSONObject.fromObject(object);
		String serialNo = obj.getString("serialNo");
		
		WorkOrder wo1 = workOrderDao.findBySerialNo(serialNo);
		WorkOrder wo2 = workOrderDao.get(wo1.getId());
		return wo2;
		
		
	}
	
	public String getWoId(String str){
		JSONObject json = JSONObject.fromObject(str);
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject obj = JSONObject.fromObject(object);
		String serialNo = obj.getString("serialNo");
		WorkOrder wo1 = workOrderDao.findBySerialNo(serialNo);
		return wo1.getId();
	}
	
	public String getOpPerson(String str){
		JSONObject json = JSONObject.fromObject(str);
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject obj = JSONObject.fromObject(object);
		String opPerson = obj.getString("opPerson");
		return opPerson;
	}
	
	@Transactional(readOnly = false)
	public void insertAttach(ApiAttach attach) {
		dao.insertAttach(attach);
	}
	
	@Transactional(readOnly = false)
	public void insertBean(ApiBean bean) {
		dao.insertBean(bean);
	}
	
	@Transactional(readOnly = false)
	public void insert(ApiWorkOrder awo) {
		dao.insert(awo);
	}
	
	@Transactional(readOnly = false)
	public void insertApiWorkOrder(String str) {
		
		JSONObject json = JSONObject.fromObject(str);
		
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject objAll = JSONObject.fromObject(object);
		JSONObject obj = new JSONObject();
		obj.put("sheetType", objAll.get("sheetType"));
		obj.put("serviceType", objAll.get("serviceType"));
		obj.put("serialNo", objAll.get("serialNo"));
		obj.put("serSupplier", objAll.get("serSupplier"));
		obj.put("serCaller", objAll.get("serCaller"));
		obj.put("callerPwd", objAll.get("callerPwd"));
		obj.put("callTime", objAll.get("callTime"));
		obj.put("opPerson", objAll.get("opPerson"));
		obj.put("opCorp", objAll.get("opCorp"));
		obj.put("opDepart", objAll.get("opDepart"));
		obj.put("opContact", objAll.get("opContact"));
		obj.put("opTime", objAll.get("opTime"));
		
		log.error(obj);
		ApiAttach att = new ApiAttach();
		ApiBean bea = new ApiBean();
		
		if(objAll.has("attachRef")){
			JSONArray attachRef = objAll.getJSONArray("attachRef");
			for(int i=0;i<attachRef.size();i++){
				JSONObject attach = attachRef.getJSONObject(i);
				attach.put("serialNo", objAll.get("serialNo"));
				att = (ApiAttach) JSONObject.toBean(attach, ApiAttach.class);
				dao.insertAttach(att);
			}
		}
		if(json.has("beans")){
			JSONArray beans = json.getJSONArray("beans");
			for(int i=0;i<beans.size();i++){
				JSONObject bean = beans.getJSONObject(i);
				bean.put("serialNo", objAll.get("serialNo"));
				bea = (ApiBean) JSONObject.toBean(bean, ApiBean.class);
				dao.insertBean(bea);
			}
		}
		if(par.has("serialNo")){
			String serialNo = par.getString("serialNo");
			par.remove("serialNo");
			par.put("serialNo1", serialNo);
		}
		JSONObject wo = new JSONObject();
		wo.putAll(obj);
		wo.putAll(par);
		wo.remove("beans");
		wo.remove("attachRef");
		ApiWorkOrder awo = (ApiWorkOrder) JSONObject.toBean(wo, ApiWorkOrder.class);
		dao.insert(awo);
	}

	@Transactional(readOnly = false)
	public void insertWorkOrder(String str) {
		
		JSONObject json = JSONObject.fromObject(str);
		
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject objAll = JSONObject.fromObject(object);
		JSONObject obj = new JSONObject();
		obj.put("sheetType", objAll.get("sheetType"));
		obj.put("serviceType", objAll.get("serviceType"));
		obj.put("serialNo", objAll.get("serialNo"));
		obj.put("serSupplier", objAll.get("serSupplier"));
		obj.put("serCaller", objAll.get("serCaller"));
		obj.put("callerPwd", objAll.get("callerPwd"));
		obj.put("callTime", objAll.get("callTime"));
		obj.put("opPerson", objAll.get("opPerson"));
		obj.put("opCorp", objAll.get("opCorp"));
		obj.put("opDepart", objAll.get("opDepart"));
		obj.put("opContact", objAll.get("opContact"));
		obj.put("opTime", objAll.get("opTime"));
		
		
		ApiAttach att = new ApiAttach();
		ApiBean bea = new ApiBean();
		WorkOrder workOrder = new WorkOrder();
		String fileUrl = "";
		if(objAll.has("attachRef")){
			JSONArray attachRef = objAll.getJSONArray("attachRef");
			for(int i=0;i<attachRef.size();i++){
				JSONObject attach = attachRef.getJSONObject(i);
				attach.put("serialNo", objAll.get("serialNo"));
				att = (ApiAttach) JSONObject.toBean(attach, ApiAttach.class);
				att.setAttachType("1");
				String attachPath = att.getAttachPath()+"/"+att.getAttachName();
				att.setAttachPath(attachPath);
				workOrderDao.insertAttach(att);
				
				fileUrl += "|/NumberOne/userfiles/"+attachPath;
			}
			
		}
		if(json.has("beans")){
			JSONArray beans = json.getJSONArray("beans");
			for(int i=0;i<beans.size();i++){
				JSONObject bean = beans.getJSONObject(i);
				bean.put("serialNo", objAll.get("serialNo"));
				bea = (ApiBean) JSONObject.toBean(bean, ApiBean.class);
				workOrderDao.insertBean(bea);
			}
		}
		if(par.has("serialNo")){
			String serialNo = par.getString("serialNo");
			par.remove("serialNo");
			par.put("serialNo1", serialNo);
		}
		JSONObject wo = new JSONObject();
		wo.putAll(obj);
		wo.putAll(par);
		wo.remove("beans");
		wo.remove("attachRef");
		workOrder = (WorkOrder) JSONObject.toBean(wo, WorkOrder.class);
		if(par.get("urgentDegree").equals("紧急")){
			workOrder.setWobj("error");
		}if(par.get("upgdCmplntsFlag").equals("是")){
			workOrder.setWobj("warning");
		}
		workOrder.setFiles(fileUrl);
		workOrder.setState("1");
		workOrderDao.insert(workOrder);
	}
	
	/**
	 * 判断工单重复
	 * @param str
	 * @return 派发为false，重派为true
	 * @throws Exception 
	 */
	public boolean repetition(String str) throws Exception{
		JSONObject json = JSONObject.fromObject(str);
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject obj = JSONObject.fromObject(object);
		String serialNo = obj.getString("serialNo");
		WorkOrder wo = workOrderDao.findBySerialNo(serialNo);
		try {
			if(StringUtils.isEmpty(wo)){
				return false;
			}
		} catch (Exception e) {
			throw e;
		}
		return true;
	}
	
	//归档
	@Transactional(readOnly = false)
	public void archive(String str) {
		WorkOrder wo = this.getWo(str);
		wo.setState("5");
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String closeDesc = params.getString("closeDesc");
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("归档");
		operation.setOperationTime(new Date());
		operation.setContent(closeDesc);
		operationService.insert(operation);
		workOrderDao.update(wo);
	}
	
	/**
	 * 重派
	 * @param str
	 */
	@Transactional(readOnly = false)
	public void reDistribute(String str) {
		WorkOrder wo = this.getWo(str);
		wo.setState("1");
		String url = wo.getFiles();
		
		JSONObject json = JSONObject.fromObject(str);
		JSONObject par = (JSONObject) json.get("params");
		String object = (String) par.get("object");
		JSONObject objAll = JSONObject.fromObject(object);
		logger.debug("---------------重派--------------"+objAll.get("serialNo"));
		ApiAttach att = new ApiAttach();
		if(objAll.has("attachRef")){
			JSONArray attachRef = objAll.getJSONArray("attachRef");
			for(int i=0;i<attachRef.size();i++){
				JSONObject attach = attachRef.getJSONObject(i);
				attach.put("serialNo", objAll.get("serialNo"));
				att = (ApiAttach) JSONObject.toBean(attach, ApiAttach.class);
				att.setAttachType("1");
				String attachPath = att.getAttachPath()+"/"+att.getAttachName();
				att.setAttachPath(attachPath);
				workOrderDao.insertAttach(att);
				url += "|/NumberOne/userfiles/"+attachPath;
			}
		}
		List<ApiAttach> list = workOrderDao.findAttachBySeriaNo(objAll.getString("serialNo"));
		for (ApiAttach apiAttach : list) {
			apiAttach.setAttachType("1");
			workOrderDao.insertAttach(apiAttach);
		}
		logger.debug("--------------地址--------------------"+url);
		wo.setFiles(url);
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("重派");
		operation.setSendTo("工单池");
		operation.setOperationTime(new Date());
		operationService.insert(operation);
		workOrderDao.update(wo);
	}
	
	//撤单
	@Transactional(readOnly = false)
	public void revoke(String str) {
		WorkOrder wo = this.getWo(str);
		wo.setState("0");
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String cancelAdvice = params.getString("cancelAdvice");
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("撤单");
		operation.setOperationTime(new Date());
		operation.setContent(cancelAdvice);
		operationService.insert(operation);
		workOrderDao.update(wo);
	}
	
	//催单
	@Transactional(readOnly = false)
	public void urge(String str) {
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String urgeAdvice = params.getString("urgeAdvice");
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("催单");
		operation.setOperationTime(new Date());
		operation.setContent(urgeAdvice);
		operationService.insert(operation);
	}
	
	//中途意见
	@Transactional(readOnly = false)
	public void suggestion(String str) {
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String suggestion = params.getString("suggestion");
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("中途意见");
		operation.setOperationTime(new Date());
		operation.setContent(suggestion);
		operationService.insert(operation);
	}
	
	//退回
	@Transactional(readOnly = false)
	public void retreat(String str) {
		WorkOrder wo = this.getWo(str);
		wo.setState("1");
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String withdrawDesc = params.getString("withdrawDesc");
		Operation operation = new Operation();
		operation.setOperationUser("在线客服"+this.getOpPerson(str));
		operation.setWorkOrderId(this.getWoId(str));
		operation.setOperationName("退回");
		operation.setOperationTime(new Date());
		operation.setContent(withdrawDesc);
		operationService.insert(operation);
		workOrderDao.update(wo);
	}
	
	//进度查询
	@Transactional(readOnly = false)
	public JSONObject getSchedule(String str) {
		JSONObject json = JSONObject.fromObject(str);
		JSONObject params = (JSONObject) json.get("params");
		String workItemId = params.getString("workItemId");
		WorkOrder wo1 = workOrderDao.findBySerialNo(workItemId);
		WorkOrder wo2 = workOrderDao.get(wo1.getId());
		String state = wo2.getState();
		JSONObject rtn = new JSONObject();
		if(!StringUtils.isEmpty(state)){
			String serialNo = wo2.getSerialNo();
			rtn.put("rtnCode", "0");
			rtn.put("eomsId", wo2.getId());
			rtn.put("workItemId", serialNo);
			if(state.equals("0")){
				rtn.put("schedule", serialNo+"号工单已经被客服撤单");
			}else if (state.equals("1")) {
				rtn.put("schedule", serialNo+"号工单还未被领取");
			}else if (state.equals("2")) {
				String userName = systemService.getUser(wo2.getBelong()).getName();
				rtn.put("schedule", serialNo+"号工单正在"+userName+"处处理");
			}else if (state.equals("3")){
				String officeName = officeService.get(wo2.getBelong()).getName();
				rtn.put("schedule", serialNo+"号工单正在"+officeName+"部门等待领取");
			}else if (state.equals("4")){
				rtn.put("schedule", serialNo+"号工单已经回复客服");
			}else if (state.equals("5")){
				rtn.put("schedule", serialNo+"号工单已经归档");
			}
		}
		return rtn;
	}
}
